package com.cty.B_SpecialDataStructures.B_Queue.QueueArray;

import com.cty.F_common.DataItem;

/**
 * @Auther: cty
 * @Date: 2020/6/14 17:07
 * @Description: 数组实现队列（无nItems字段）
 * 应用场景：
 *      数据量可预测或内存充足时使用
 *          频繁插入删除时考虑使用 无nItems字段的数组实现队列。
 * 重要操作：
 *      ① peek(): DataItem    O(1)
 *      ② insert(DataItem): boolean    O(1)
 *      ③ remove(): DataItem    O(1)
 * @version: 1.0
 */
public class QueueArray2 {
    private int maxSize;
    private DataItem[] array;
    private int front;
    private int rear;

    public QueueArray2(int queueSize){
        maxSize = queueSize + 1;
        array = new DataItem[maxSize];
        front = 0;
        rear = -1;
    }

    public boolean isEmpty(){
        return ((rear+1==front) || (rear-(maxSize-1)==front));
    }

    public boolean isFull(){
        return ((rear+2==front) || (rear-(maxSize-2)==front));
    }

    public int size(){
        if(isEmpty())
            return 0;

        if(rear >= front)
            return (rear - front + 1);
        else
            //return (maxSize-1 - front + 1) + (rear + 1);
            return (maxSize - front + rear + 1);
    }

    public void displayQueue(){
        if(isEmpty())
            return;

        if(rear >= front){
            for(int i=front; i<=rear; i++)
                System.out.print(array[i].getKey() + " ");
        }else{
            for(int i=front; i<=maxSize-1; i++)
                System.out.print(array[i].getKey() + " ");
            for(int i=0; i<=rear; i++)
                System.out.print(array[i].getKey() + " ");
        }
        System.out.println();
    }

    public DataItem peek(){
        if(isEmpty())
            return null;

        return array[front];
    }

    public boolean insert(DataItem item){
        if(isFull())
            return false;

        rear = (rear + 1) % maxSize;
        array[rear] = item;
        return true;
    }

    public DataItem remove(){
        if(isEmpty())
            return null;

        DataItem temp = array[front];
        front = (front + 1) % maxSize;
        return temp;
    }

}  // end QueueArray2
